//
//  Net.swift
//  BBetter
//
//  Created by Gmc on 2020/3/7.
//  Copyright © 2020 Gmc. All rights reserved.
//

import Foundation
var dict:[String: Any] = [String: Any]()
var callBack:(([String: Any])->Void)?
enum requestType {
    case get
    case post
}

var baseUrl:String = "http://192.168.3.2:8000/"

struct Net {
    static func loadData(type:requestType, para:[String: Any]? = nil, url: String, callback: @escaping ([String: Any])->Void) {
        if type == .get {
            Net().get(url: baseUrl + url, callback: callback)
        } else {
            if let _ = para {
                Net().post(url: baseUrl + url, para: para!, callback: callback)
            } else {
                dict["success"] = false
                dict["msgInfo"] = "参数不能为空"
                callback(dict)
            }
        }
    }
    
    private func get(url: String, callback: @escaping ([String: Any])->Void) {
        let url = URL(string: url)!
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)
        let task = session.dataTask(with: url) { (data: Data?, response:URLResponse?, error:Error?) in
            if let _ = error {
                dict["success"] = false
                dict["msgInfo"] = "网络数据获取失败"
                DispatchQueue.main.async {
                    /// back to main thread
                    callback(dict)
                }
            } else {
                if let _ = data {
                    do {
                        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                        let dic = json as! Dictionary<String, Any>
                        dict["success"] = true
                        dict["msgInfo"] = ""
                        dict["data"] = dic["data"]
                        DispatchQueue.main.async {
                            /// back to main thread
                            callback(dict)
                        }
                    } catch _ {
                        dict["success"] = false
                        dict["msgInfo"] = "网络数据解析失败"
                        DispatchQueue.main.async {
                            /// back to main thread
                            callback(dict)
                        }
                    }
                } else {
                    dict["success"] = false
                    dict["msgInfo"] = "网络数据不可用"
                    DispatchQueue.main.async {
                        /// back to main thread
                        callback(dict)
                    }
                }
            }
        }
        task.resume()
    }
    
    private func post(url: String, para:[String: Any], callback: @escaping ([String: Any])->Void) {
        let url = URL(string: url)!
        var request:URLRequest = URLRequest(url: url)
        request.httpMethod = "POST"
        let value: NSData! = try? JSONSerialization.data(withJSONObject: para, options: []) as NSData
        let postString:NSString = NSString(data:value as Data,encoding: String.Encoding.utf8.rawValue)!
        request.httpBody = postString.data(using: String.Encoding.utf8.rawValue)
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)
        let task = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            if let _ = error {
                dict["success"] = false
                dict["msgInfo"] = "网络数据获取失败"
                DispatchQueue.main.async {
                    /// back to main thread
                    callback(dict)
                }
            } else {
                if let _ = data {
                    do {
                        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                        let dic = json as! Dictionary<String, Any>
                        dict["success"] = true
                        dict["msgInfo"] = ""
                        dict["data"] = dic["data"]
                        DispatchQueue.main.async {
                            /// back to main thread
                            callback(dict)
                        }
                    } catch _ {
                        dict["success"] = false
                        dict["msgInfo"] = "网络数据解析失败"
                        DispatchQueue.main.async {
                            /// back to main thread
                            callback(dict)
                        }
                    }
                } else {
                    dict["success"] = false
                    dict["msgInfo"] = "网络数据不可用"
                    DispatchQueue.main.async {
                        /// back to main thread
                        callback(dict)
                    }
                }
            }
        }
        task.resume()
    }
}
